﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Utility;
using System.Configuration;

namespace _411Server
{
    public partial class Form1 : Form
    {
        public Socket ServerSocket { get; set; }

        public IPEndPoint ServerInfo { get; set; }
        Thread _thread;

        private readonly string _serverIp = ConfigurationManager.AppSettings["ServerIp"];
        private readonly int _port = int.Parse(ConfigurationManager.AppSettings["Port"]);

        public Form1()
        {
            InitializeComponent();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            btnStart.Enabled = false;
            btnStop.Enabled = true;
            ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //提供一个 IP 地址，指示服务器应侦听所有网络接口上的客户端活动
            IPAddress ip = IPAddress.Parse(_serverIp);
            ServerInfo = new IPEndPoint(ip, _port);
            ServerSocket.Bind(ServerInfo); //将SOCKET接口和IP端口绑定
            ServerSocket.Listen(10); //开始监听，并且挂起数为10
            Thread thread = new Thread(ServerStart) {IsBackground = true};
            thread.Start();
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            btnStart.Enabled = true;
            btnStop.Enabled = false;
            ServerSocket.Close();
        }

        //运行服务器线程

        private void ServerStart()
        {
            try
            {
                while (true)
                {
                    Socket s = ServerSocket.Accept();
                    int id = Manage.Id++;
                    Manage.SocketIdTable.Add(id.ToString(), s);
                    byte[] recvBytes = Encoding.Unicode.GetBytes((id).ToString());
                    s.Send(recvBytes);
                    recvBytes = new byte[1024];
                    int bytes = s.Receive(recvBytes, recvBytes.Length, 0);
                    String name = Encoding.Unicode.GetString(recvBytes, 0, bytes);
                    User user = new User { Id = id.ToString(), Name = name };
                    Manage.Users.Add(user);
                    Comunicate com = new Comunicate(this, s);
                    _thread = new Thread(com.Run);
                    com.SetThread(_thread);
                    _thread.IsBackground = true;
                    _thread.Start();
                    while (Manage.Users.Count >= 2)
                    {
                        User user1 = (User)Manage.Users[0];
                        User user2 = (User)Manage.Users[1];
                        Socket s1 = (Socket)Manage.SocketIdTable[user1.Id];
                        Socket s2 = (Socket)Manage.SocketIdTable[user2.Id];
                        MyMessage message1 = new MyMessage();
                        MyMessage message2 = new MyMessage();
                        message1.MessageType = MessageType.MESSAGE_USER;
                        message2.MessageType = MessageType.MESSAGE_USER;
                        message1.Accepter = user2;
                        message2.Accepter = user1;
                        s1.Send(Serialize.DoSerialize(message1));
                        s2.Send(Serialize.DoSerialize(message2));
                        Manage.Users.RemoveAt(0);
                        Manage.Users.RemoveAt(0);
                    }
                }
            }
            catch
            {
                if (_thread != null)
                    _thread.Abort();
            }
        }
    }
}
